import React, { useEffect, useState } from 'react';
import { Card, Form, Button } from 'react-bootstrap';

const ModManagement = ({ 
  config, 
  setConfig,
  availableMods,
  serverStatus
}) => {
  // 组件内部默认配置
  const defaultModConfig = {
    mods: [],
    addAtPrefix: false,
    modsDirectory: '../DayZServer/mods'
  };

  // 组件内部状态，用于表单输入临时存储
  const [localConfig, setLocalConfig] = useState(defaultModConfig);

  // 当外部config变化时，更新内部localConfig
  useEffect(() => {
    const mergedConfig = {
      ...defaultModConfig,
      ...config
    };
    setLocalConfig(mergedConfig);
  }, [config]);

  // 处理配置变更，同时更新本地状态和全局配置
  const handleConfigChange = (key, value) => {
    setLocalConfig(prev => ({ ...prev, [key]: value }));
    setConfig(prev => ({ ...prev, [key]: value }));
  };

  // 模组管理相关函数
  const addMod = (modFolder, type) => {
    const useAtPrefix = localConfig.addAtPrefix;
    const modName = useAtPrefix ? `@${modFolder}` : modFolder;
    const modPath = `${localConfig.modsDirectory}/${modFolder}`;
    
    // 检查是否已存在相同名称和类型的模组
    const existingModIndex = localConfig.mods.findIndex(
      mod => mod.name === modName && mod.type === type
    );
    
    // 如果存在，则移除旧的
    const newMods = [...localConfig.mods];
    if (existingModIndex !== -1) {
      newMods.splice(existingModIndex, 1);
    }
    
    // 添加新的模组
    newMods.push({ name: modName, type: type, path: modPath });
    handleConfigChange('mods', newMods);
  };
  
  const removeMod = (index) => {
    const newMods = [...localConfig.mods];
    newMods.splice(index, 1);
    handleConfigChange('mods', newMods);
  };
  
  const moveMod = (index, direction) => {
    if ((direction === -1 && index === 0) || (direction === 1 && index === localConfig.mods.length - 1)) {
      return;
    }
    
    const newMods = [...localConfig.mods];
    const temp = newMods[index];
    newMods[index] = newMods[index + direction];
    newMods[index + direction] = temp;
    handleConfigChange('mods', newMods);
  };
  
  const clearAllMods = () => {
    if (window.confirm('确定要清空所有模组吗？')) {
      handleConfigChange('mods', []);
    }
  };

  // 确保mods存在
  const mods = localConfig.mods || [];

  return (
    <Card className="h-100 border-3 shadow-medium" style={{backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(15px)', borderColor: '#d32f2f', boxShadow: '0 0 20px rgba(211, 47, 47, 0.5), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 0 10px rgba(211, 47, 47, 0.2)'}}>
      <Card.Header style={{backgroundColor: 'rgba(40, 40, 40, 0.7)', backdropFilter: 'blur(15px)'}}>
        <h3 style={{color: 'var(--primary-color)'}}>模组管理</h3>
      </Card.Header>
      <Card.Body style={{color: '#ffffff', maxHeight: '70vh', overflowY: 'auto'}}>
        <Form>
          <div className="row mb-3">
            {/* 启用模组前缀 */}
            <div className="col-md-6">
              <Form.Group>
                <Form.Check 
                  type="checkbox" 
                  checked={localConfig.addAtPrefix} 
                  onChange={(e) => handleConfigChange('addAtPrefix', e.target.checked)} 
                  label="启用模组前缀" 
                  style={{color: '#ffffff'}}
                />
                <small style={{color: '#cccccc', display: 'block', marginTop: '5px'}}>勾选后使用官方的加载目录前缀，取消为自定义目录名</small>
              </Form.Group>
            </div>
            
            {/* 模组存储目录 */}
            <div className="col-md-6">
              <Form.Group>
                <Form.Label style={{color: '#ffffff'}}>模组存储目录</Form.Label>
                <Form.Control
                  type="text"
                  value={localConfig.modsDirectory}
                  onChange={(e) => handleConfigChange('modsDirectory', e.target.value)}
                  style={{backgroundColor: 'rgba(0, 0, 0, 0.4)', borderColor: '#555', color: '#ffffff'}}
                  placeholder="请输入模组目录路径"
                />
              </Form.Group>
            </div>
          </div>
          
          {/* 模组列表（服务器未启动时显示） */}
          {serverStatus !== 'running' && serverStatus !== 'paused' && (
            <div className="mb-4">
              <div className="d-flex justify-content-between align-items-center mb-2">
                <h5>本地模组列表</h5>
                <div className="d-flex">
                  <div className="text-center" style={{width: '100px'}}>
                    <span>客户端模组</span>
                  </div>
                  <div className="text-center" style={{width: '100px'}}>
                    <span>服务端模组</span>
                  </div>
                </div>
              </div>
              {availableMods.length > 0 ? (
                <div className="row">
                  {availableMods.map((modFolder, index) => {
                    // 检查该模组是否已作为客户端或服务端模组加载
                    const useAtPrefix = localConfig.addAtPrefix || false;
                    const modName = useAtPrefix ? `@${modFolder}` : modFolder;
                    const isClientMod = mods.some(mod => mod.name === modName && mod.type === 'client');
                    const isServerMod = mods.some(mod => mod.name === modName && mod.type === 'server');
                    
                    return (
                      <div key={index} className="col-md-12 mb-2">
                        <div className="d-flex justify-content-between align-items-center p-2 bg-secondary bg-opacity-20 rounded">
                          <span>{modFolder}</span>
                          <div className="d-flex">
                            <div className="text-center" style={{width: '100px'}}>
                              <div className="form-check d-flex justify-content-center align-items-center">
                                <input 
                                  className="form-check-input" 
                                  type="radio" 
                                  name={`modType-${index}`} 
                                  id={`client-${index}`}
                                  checked={isClientMod}
                                  onClick={() => addMod(modFolder, 'client')}
                                />
                              </div>
                            </div>
                            <div className="text-center" style={{width: '100px'}}>
                              <div className="form-check d-flex justify-content-center align-items-center">
                                <input 
                                  className="form-check-input" 
                                  type="radio" 
                                  name={`modType-${index}`} 
                                  id={`server-${index}`}
                                  checked={isServerMod}
                                  onClick={() => addMod(modFolder, 'server')}
                                />
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <div className="text-muted p-3 bg-light bg-opacity-10 rounded">
                  未找到可用模组，将自动刷新...
                </div>
              )}
            </div>
          )}
          
          {(mods && mods.length > 0) && (
            <div>
              <div className="d-flex justify-content-between align-items-center mb-2">
                <h5>加载模组列表</h5>
                <div>
                  <Button variant="danger" size="sm" onClick={clearAllMods}>
                    清空所有模组
                  </Button>
                </div>
              </div>
              
              {/* 客户端和服务器模组双列显示 */}
              <div className="row mb-4">
                {/* 客户端模组列 */}
                <div className="col-md-6">
                  <h6 className="mb-2 text-primary">客户端模组</h6>
                  {mods.filter(mod => mod.type === 'client').length > 0 ? (
                    mods.filter(mod => mod.type === 'client').map((mod, index) => {
                      const actualIndex = mods.findIndex(m => m.name === mod.name && m.path === mod.path);
                      return (
                        <div key={`client-${actualIndex}`} className="mb-2">
                          <div className="d-flex flex-column gap-1 p-3 bg-dark bg-opacity-40 rounded border border-secondary border-opacity-30">
                            <div className="d-flex justify-content-between align-items-center">
                              <span className="font-weight-bold">
                                {mod.name}
                              </span>
                              <div className="d-flex gap-1">
                                <Button 
                                  variant="secondary" 
                                  size="sm" 
                                  onClick={() => moveMod(actualIndex, -1)}
                                  disabled={actualIndex === 0}
                                >
                                  ↑
                                </Button>
                                <Button 
                                  variant="secondary" 
                                  size="sm" 
                                  onClick={() => moveMod(actualIndex, 1)}
                                  disabled={actualIndex === mods.length - 1}
                                >
                                  ↓
                                </Button>
                                <Button 
                                  variant="danger" 
                                  size="sm" 
                                  onClick={() => removeMod(actualIndex)}
                                >
                                  删除
                                </Button>
                              </div>
                            </div>

                            <div className="text-xs text-secondary">
                              路径: {mod.path}
                            </div>
                          </div>
                        </div>
                      );
                    })
                  ) : (
                    <div className="d-flex flex-column gap-1 p-3 bg-dark bg-opacity-40 rounded border border-secondary border-opacity-30">
                      <div className="text-center text-secondary text-sm">
                        暂无客户端模组
                      </div>
                    </div>
                  )}
                </div>
                
                {/* 服务器模组列 */}
                <div className="col-md-6">
                  <h6 className="mb-2 text-info">服务器模组</h6>
                  {mods.filter(mod => mod.type === 'server').length > 0 ? (
                    mods.filter(mod => mod.type === 'server').map((mod, index) => {
                      const actualIndex = mods.findIndex(m => m.name === mod.name && m.path === mod.path);
                      return (
                        <div key={`server-${actualIndex}`} className="mb-2">
                          <div className="d-flex flex-column gap-1 p-3 bg-dark bg-opacity-40 rounded border border-secondary border-opacity-30">
                            <div className="d-flex justify-content-between align-items-center">
                              <span className="font-weight-bold">
                                {mod.name}
                              </span>
                              <div className="d-flex gap-1">
                                <Button 
                                  variant="secondary" 
                                  size="sm" 
                                  onClick={() => moveMod(actualIndex, -1)}
                                  disabled={actualIndex === 0}
                                >
                                  ↑
                                </Button>
                                <Button 
                                  variant="secondary" 
                                  size="sm" 
                                  onClick={() => moveMod(actualIndex, 1)}
                                  disabled={actualIndex === mods.length - 1}
                                >
                                  ↓
                                </Button>
                                <Button 
                                  variant="danger" 
                                  size="sm" 
                                  onClick={() => removeMod(actualIndex)}
                                >
                                  删除
                                </Button>
                              </div>
                            </div>

                            <div className="text-xs text-secondary">
                              路径: {mod.path}
                            </div>
                          </div>
                        </div>
                      );
                    })
                  ) : (
                    <div className="d-flex flex-column gap-1 p-3 bg-dark bg-opacity-40 rounded border border-secondary border-opacity-30">
                      <div className="text-center text-secondary text-sm">
                        暂无服务器模组
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </Form>
      </Card.Body>
    </Card>
  );
}

export default ModManagement;